package com.woniuxy.yogaapp.service.imp;

import com.woniuxy.yogaapp.mapper.*;
import com.woniuxy.yogaapp.pojo.*;
import com.woniuxy.yogaapp.service.RelationService;
import com.woniuxy.yogaapp.util.TimeUtil;
import org.apache.ibatis.annotations.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;

/**
 * Relation的Service层，处理业务逻辑
 */
@Service("relationService")

public class RelationServiceImp implements RelationService {

    @Resource
    private AttentionMapper attentionMapper;
    @Resource
    private ChatMapper chatMapper;
    @Resource
    private UserRolesMapper userRolesMapper;
    @Resource
    private StudentMapper studentMapper;
    @Resource
    private CoachMapper coachMapper;
    @Resource
    private FriendsMapper friendsMapper;
    @Resource
    private ConsultationMapper consultationMapper;

    /**
     * 添加关注
     * @param attention
     * @param chat
     * @return
     */
    @Transactional
    @Override
    public String addAttention(Attention attention, Chat chat) {
        //返会的信息
        String result = "添加关注失败，请联系管理员";

        //查询是否已经关注
        Integer Aid = attentionMapper.isAttentionOkByUid(attention.getMe(), attention.getOther());
       
        if (Aid != null && Aid > 0) {
            result = "你已经关注用户，请不要重复关注";
            return result;
        }
        //查看对方是否关注我
        Integer Aid1 = attentionMapper.isAttentionOkByUid(attention.getOther(), attention.getMe());

        //发送的信息
        String info = "";
        //用户的昵称
        String nickName = "";
        //用户的头像
        String image = "";
        //根据uid查找用户的权限
        UserRoles meRoles = userRolesMapper.findRolesByUid(attention.getMe());
        System.out.println(meRoles+"999999999999999999999999999999999999999");
        Friends otherfriends = new Friends();
        //查询用户的昵称和头像
        switch (meRoles.getRid()) {
            case 2:
                Student student = new Student();
                student.setUid(attention.getMe());
                student = studentMapper.findStudentByUid(student);
                nickName = student.getSnickname();
                image = student.getSimage();
                break;
            case 3:
                Coach coach = new Coach();
                coach.setUid(attention.getMe());
                coach = coachMapper.findCoachByUid(coach);
                nickName = coach.getCnickname();
                image = coach.getCimage();
                break;
            default:
                return result;
        }
        //生成通知，通知other被关注

        if (Aid1 != null && Aid1 > 0) {
            info = nickName + "关注了你，你们已经自动成为好友";
            chat.setMestype(2);
        } else {
            info = nickName + "关注了你，请问你是否关注" + info;
        }
        chat.setMes(info);

        //根据uid查找被关注人的权限
        UserRoles otherRoles = userRolesMapper.findRolesByUid(attention.getOther());
        //设置被关注人的角色
        attention.setRoles(otherRoles.getRid());
        //查询关注人的信息（根据不同的角色到不同的表中查询）
        switch (otherRoles.getRid()) {
            case 2:
                //将信息复制到关注对象中
                Student student = new Student();
                student.setUid(attention.getOther());
                student = studentMapper.findStudentByUid(student);
                attention.setAimage(student.getSimage());
                attention.setAname(student.getSnickname());
                break;
            case 3:
                //将信息复制到关注对象中
                Coach coach = new Coach();
                coach.setUid(attention.getOther());
                coach = coachMapper.findCoachByUid(coach);
                attention.setAimage(coach.getCimage());
                attention.setAname(coach.getCnickname());
                break;
            default:
                return result;
        }


      
        //数据库中添加关注状态
        int attentionRow = attentionMapper.addAttention(attention);

        //数据库中添加关注通知
        int chatRow = chatMapper.addChat(chat);

        if (attentionRow == 0 || chatRow == 0) {
            return result;
        }
        result = "关注成功";

        //判断是否成为好友
        if (Aid1 != null && Aid1 > 0) {
            Friends meFriend = new Friends(attention.getMe(),attention.getOther(),attention.getAname(),attention.getAimage(),otherRoles.getRid());
            Friends otherFriends = new Friends(attention.getOther(), attention.getMe(), nickName, image,meRoles.getRid());
            //注册成为好友(数据库中添加相互好友信息)
            int friendRow = friendsMapper.addFriends(meFriend);
            int friendRow2 = friendsMapper.addFriends(otherFriends);
            if (friendRow <= 0 || friendRow2 <= 0) {
                result = "添加关注失败，请联系管理员";
            } else {
                result = "恭喜你们已经成为好友";
            }
        }

        return result;
    }




    /**
     * 取消关注业务逻辑
     * @param attention
     * @param chat
     * @return
     */
    @Override
    @Transactional
    public String cancelAttention(Attention attention, Chat chat) {
        //返会的信息
        String result = "取消关注失败，请联系管理员";

        //查询是否已经关注
        Integer Aid = attentionMapper.isAttentionOkByUid(attention.getMe(), attention.getOther());
        if (Aid == null || Aid <= 0) {
            result = "你没有关注该对象";
            return result;
        }

        //查看对方是否关注我
        Integer Aid1 = attentionMapper.isAttentionOkByUid(attention.getOther(), attention.getMe());

        //发送的信息
        String info = "";
        //用户的昵称
        String nickName = "";
        //根据uid查找用户的权限
        UserRoles userRoles = userRolesMapper.findRolesByUid(attention.getMe());
        //查询用户的昵称
        switch (userRoles.getRid()) {
            case 2:
                Student student = new Student();
                student.setUid(attention.getMe());
                student = studentMapper.findStudentByUid(student);
                nickName = student.getSnickname();
                break;
            case 3:
                Coach coach = new Coach();
                coach.setUid(attention.getMe());
                coach = coachMapper.findCoachByUid(coach);
                nickName = coach.getCnickname();
                break;
            default:
                return result;
        }
        //生成通知，通知other被取消关注
        if (Aid1 != null && Aid1 > 0) {
            info = nickName + "取消关注你了，请问是否对"+nickName+"取消关注";
        } else {
            info = nickName + "取消关注你";
            chat.setMestype(2);
        }
        chat.setMes(info);

        //数据库中取消关注状态
        int attentionRow = attentionMapper.cancelAttention(attention);

        //数据库中添加取关注通知
        int chatRow = chatMapper.addChat(chat);

        if (attentionRow == 0 || chatRow == 0) {
            return result;
        }
        result = "取关成功";

        //判断是否是好友
        if (Aid1 != null && Aid1 > 0) {
            //删除好友信息(数据库中删除好友信息)
            int friendRow = friendsMapper.deleteFriends(attention.getMe(), attention.getOther());
            int friendRow2 = friendsMapper.deleteFriends(attention.getOther(), attention.getMe());

            if (friendRow <= 0 || friendRow2 <= 0) {
                result = "取消关注失败，请联系管理员";
            } else {
                result = "取消关注成功，你们已经不是好友";

            }
        }
        //改变消息的状态
        if (result.contains("成功")) {
            Chat chat1 = new Chat();
            chat1.setSender(attention.getMe());
            chat1.setRecipient(attention.getOther());
            chatMapper.updatePrivateChat(chat1);
            chat1.setSender(attention.getOther());
            chat1.setRecipient(attention.getMe());
            chatMapper.updatePrivateChat(chat1);
        }

        return result;
    }

    /**
     * 查找用户的所有好友的名字和头像
     * @param uid
     * @return
     */
    @Override
    public List<Friends> findFriends(Integer uid) {
        //获取好友集合
        List<Friends> friendsByUid = friendsMapper.findFriendsByUid(uid);
        for (Friends friends : friendsByUid) {
            //获取好友未读信息
            Integer unreade = chatMapper.findUnreadeByUid(friends.getFriend(), friends.getMe());
            friends.setUnread(unreade);
        }
        return friendsByUid;
    }

    /**
     * 查找用户的所有关注人的名字和头像
     * @param uid
     * @return
     */
    @Override
    public List<Attention> findAttentions(Integer uid) {
        return attentionMapper.findAttentionsByUid(uid);
    }

    /**
     * 添加咨询关系
     * @param me
     * @param other
     * @return
     */
    @Override
    @Transactional
    public String addConsultation(Integer me, Integer other) {

        //查询是否已经添加咨询
        Consultation consultation = consultationMapper.findConsultation(me, other);
        if (consultation != null && consultation.getMe() != null) {
            return "你已经咨询过，请前往信息中心查看信息";
        }

        //根据uid查找用户的权限
        UserRoles meRoles = userRolesMapper.findRolesByUid(me);
        Consultation otherCon = new Consultation();
        otherCon.setMe(other);
        otherCon.setOther(me);
        otherCon.setRoles(meRoles.getRid());
        //查询用户的昵称和头像
        switch (meRoles.getRid()) {
            case 2:
                Student student = new Student();
                student.setUid(me);
                student = studentMapper.findStudentByUid(student);
                otherCon.setCname(student.getSnickname());
                otherCon.setCimage(student.getSimage());
                break;
            case 3:
                Coach coach = new Coach();
                coach.setUid(me);
                coach = coachMapper.findCoachByUid(coach);
                otherCon.setCname(coach.getCnickname());
                otherCon.setCimage(coach.getCimage());
                break;
            default:
                return "无此角色的用户";
        }

        //根据uid查找用户的权限
        UserRoles otherRoles = userRolesMapper.findRolesByUid(other);
        Consultation meCon = new Consultation();
        meCon.setMe(me);
        meCon.setOther(other);
        meCon.setRoles(otherRoles.getRid());
        //查询用户的昵称和头像
        switch (otherRoles.getRid()) {
            case 2:
                Student student = new Student();
                student.setUid(other);
                student = studentMapper.findStudentByUid(student);
                meCon.setCname(student.getSnickname());
                meCon.setCimage(student.getSimage());
                break;
            case 3:
                Coach coach = new Coach();
                coach.setUid(other);
                coach = coachMapper.findCoachByUid(coach);
                meCon.setCname(coach.getCnickname());
                meCon.setCimage(coach.getCimage());
                break;
            default:
                return "无此角色的用户";
        }


        System.out.println(meCon);
        System.out.println(otherCon);
        //数据库中添加查询状态
         int meRow = consultationMapper.addConsultation(meCon);
        int otherRow = consultationMapper.addConsultation(otherCon);

        Chat chat = new Chat();
        chat.setSender(me);
        chat.setRecipient(other);
        chat.setState("未读");
        chat.setMestime(TimeUtil.getNowDate());
        chat.setMestype(2);
        chat.setMes(otherCon.getCname()+"向你发起了咨询，快去我的咨询回复吧");

        //
        //数据库中添加咨询通知
        int chatRow = chatMapper.addChat(chat);

        if (meRow == 0 || chatRow == 0 || otherRow == 0) {
            return "添加失败，请联系管理员";
        }


        return "咨询发起成功，快去信息中心中的我的咨询询问详细信息吧";
    }

    /**
     * 根据uid查询咨询对象
     * @param uid
     * @return
     */
    @Override
    public List<Consultation> findConsultationByUid(Integer uid) {
        List<Consultation> consultationByUid = consultationMapper.findConsultationByUid(uid);
        for (Consultation consultation : consultationByUid) {
            //获取好友未读信息
            Integer unreade = chatMapper.findUnreadeByUid1(consultation.getOther(), consultation.getMe());
            consultation.setUnread(unreade);
        }
        return consultationByUid;
    }

    /**
     * 取消咨询关系
     * @param me
     * @param other
     * @return
     */
    @Override
    public String deleteConsultation(Integer me, Integer other) {

        int i =consultationMapper.deleteConsultation(me, other);
        if (i > 0) {
            Chat chat = new Chat();
            chat.setSender(me);
            chat.setRecipient(other);
            chatMapper.updateConsultationChat(chat);
            chat.setSender(other);
            chat.setRecipient(me);
            chatMapper.updateConsultationChat(chat);
            return "删除成功";
        }
        return "删除失败";
    }


}